package com.appspot.igo8poi.filter;

import com.appspot.igo8poi.model.bean.UserInfo;
import com.appspot.igo8poi.service.UserManager;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// todo: can be replaced by a web config section; it'll also allow to add admin functionality 

// http://code.google.com/appengine/docs/java/config/webxml.html#Security_and_Authentication
public class AuthenticationFilter implements Filter {

	private UserManager userManager = UserManager.getInstance();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest) servletRequest;

		UserInfo user = userManager.getCurrentUser();
		if (null == user || null == user.getUserId()) {
			response.sendRedirect(userManager.createLoginUrl(request.getRequestURI()));
		} else {
			request.setAttribute("user", user);
			request.setAttribute("isAdmin", userManager.isUserAdmin());
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	@Override
	public void destroy() {
	}
}
